package com.woniuxy.interceptor;

import com.alibaba.fastjson.JSON;
import com.woniuxy.util.JWTUtil;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.ResponseEnum;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//登录拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 步骤
     * 1.获取请求的jwt
     * 获取不到直接拦截
     * 2.用系统jwt密钥解密
     * 解不开拦截
     * 3.判断redis对应的jwp是否过期
     * 如果过期拦截
     * 4.给jwt续期
     * 5.放行
     *
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //1.获取请求的jwt(从请求头中)
        String jwt = request.getHeader("Authorization");
//        String jwt = jwt1.substring(7);
        String jsonString = JSON.toJSONString(ResponseData.fail(ResponseEnum.NOLOGIN));
        response.setContentType("application/json;charset=utf-8");
        if (jwt == null) {
            //响应的是java对象需要json对象

            response.getWriter().println( jsonString);
            return false;
        }
        //2.用系统jwt密钥解密
        if (!JWTUtil.decode(jwt)) {//必须解密 jwt和redisJWT相等但内容也肯能不一样几率低
            response.getWriter().println( jsonString);
            return false;
        }
        //3.判断redis对应的jwt是否过期，根据key到redis中查询
        Map userInfo = JWTUtil.getJWTUserInfo(jwt);
        Object id = userInfo.get("id");
        String redisJWT = stringRedisTemplate.opsForValue().get("JWT:" + id);
        String sorterRedisJWT = stringRedisTemplate.opsForValue().get("sorterJWT:" + id);
        String courierRedisJWT = stringRedisTemplate.opsForValue().get("courierJWT:" + id);
        if (jwt.equals(redisJWT)||jwt.equals(sorterRedisJWT)||jwt.equals(courierRedisJWT)) {//也可以直接判断是否为空，为空则拦截
            response.getWriter().println( jsonString);
            if(jwt.equals(redisJWT)){
                //4.给jwt续期
                stringRedisTemplate.expire("JWT:" + id, 60000, TimeUnit.SECONDS);
            }else if(jwt.equals(sorterRedisJWT)){
                //4.给jwt续期
                stringRedisTemplate.expire("sorterJWT:" + id, 60000, TimeUnit.SECONDS);
            }else if(jwt.equals(courierRedisJWT)){
                //4.给jwt续期
                stringRedisTemplate.expire("courierJWT:" + id, 60000, TimeUnit.SECONDS);
            }
            return true;
        }else{
            return false;
        }
    }
}
